<!-- 搜索 -->
<template>
  <div v-loading="isSearch">
    <div class="container">
      <div class="pt-50 pb-50">
        <div class="row mb-20">
          <div class="col-12 align-self-center main-search-form-cover m-auto">
            <p class="text-center">
              <span class="search-text-bg">搜 索</span>
            </p>
            <form action="#" class="search-header">
              <div class="input-group w-100">
                <el-autocomplete style="border: none;" :popper-append-to-body="false" class="form-control" v-model="searchInput" :fetch-suggestions="querySearchAsync"
                  :placeholder="currentTitle" @select="handleSelect">
                </el-autocomplete>
                <div class="input-group-append">
                  <button class="btn btn-search bg-white" @click="searchAll" type="submit">
                    <i class="elegant-icon icon_search"></i>
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
        <div class="row mt-80 text-center">
          <div class="col-12 font-small suggested-area">
            <h5 class="suggested font-heading mb-20 text-muted">
              <strong>{{
                  !isSearch ? "搜 索 发 现 :" : "正在努力搜索"
                }}</strong>
            </h5>
            <ul class="list-inline d-inline-block" v-if="!isSearch">
              <li class="list-inline-item" v-for="(item, i) in keywords" :key="i">
                <a href="javascript:void(0)" @click="toResult(item)">{{ item }}</a>
              </li>
            </ul>
          </div>
        </div>
        <div class="archive-header pt-50">
          <div class="container">
            <h2 class="font-weight-900">搜索中心</h2>
            <p v-if="total > 0">找到与'&nbsp;<em style='color:red;font-style:normal;'>{{searchInput}}</em >&nbsp;'有关的<em style='color:red;font-style:normal;'>{{total}}</em>个结果</p>
            <div class="bt-1 border-color-1 mt-30 mb-50"></div>
          </div>
        </div>
        <div>
          <el-empty :description="'没有找到有关 \''+searchInput+'\' 的内容'" v-if="hasNodata"></el-empty>
          <div v-for="(data,i) in res" :key="i">
            <el-row>
              <el-col :span="24">
                <article class="hover-up-2 transition-normal wow fadeInUp animated">
                  <div class="row mb-40 list-style-2">
                    <div class="col-md-4">
                      <div class="post-thumb position-relative border-radius-5">
                        <a @click="$commons.toWindodBlog(data.id)" href="javascript:void(0)" style="white-space:nowrap;">
                          <div class="img-hover-slide border-radius-5 position-relative"
                            :style="{ backgroundImage: 'url(' + data.background + ')',widget:'100px' }">
                            <!-- <span v-if="data.status != -1" :class="'top-left-icon'+' '+icons[data.status].c"><i
                  :class="'fa'+' '+ icons[data.status].i"></i></span> -->
                          </div>
                        </a>
                        <ul class="social-share">
                          <li><a href="#"><i class="elegant-icon social_share"></i></a></li>
                          <li><a class="fb" href="javascript:void(0)" title="暂时不可用" target="_blank"><svg
                                class="Zi Zi--WeChat Login-socialIcon" fill="#fff" viewBox="0 0 24 24" width="20"
                                height="20">
                                <path
                                  d="M2.224 21.667s4.24-1.825 4.788-2.056C15.029 23.141 22 17.714 22 11.898 22 6.984 17.523 3 12 3S2 6.984 2 11.898c0 1.86.64 3.585 1.737 5.013-.274.833-1.513 4.756-1.513 4.756zm5.943-9.707c.69 0 1.25-.569 1.25-1.271a1.26 1.26 0 0 0-1.25-1.271c-.69 0-1.25.569-1.25 1.27 0 .703.56 1.272 1.25 1.272zm7.583 0c.69 0 1.25-.569 1.25-1.271a1.26 1.26 0 0 0-1.25-1.271c-.69 0-1.25.569-1.25 1.27 0 .703.56 1.272 1.25 1.272z"
                                  fill-rule="evenodd"></path>
                              </svg></a></li>
                          <li><a class="tw" href="javascript:void(0)" target="_blank" title="分享到QQ"><svg
                                class="Zi Zi--QQ Login-socialIcon" fill="#fff" viewBox="0 0 24 24" width="20"
                                height="20">
                                <path
                                  d="M12.003 2c-2.265 0-6.29 1.364-6.29 7.325v1.195S3.55 14.96 3.55 17.474c0 .665.17 1.025.281 1.025.114 0 .902-.484 1.748-2.072 0 0-.18 2.197 1.904 3.967 0 0-1.77.495-1.77 1.182 0 .686 4.078.43 6.29 0 2.239.425 6.287.687 6.287 0 0-.688-1.768-1.182-1.768-1.182 2.085-1.77 1.905-3.967 1.905-3.967.845 1.588 1.634 2.072 1.746 2.072.111 0 .283-.36.283-1.025 0-2.514-2.166-6.954-2.166-6.954V9.325C18.29 3.364 14.268 2 12.003 2z"
                                  fill-rule="evenodd"></path>
                              </svg></a></li>
                          <li><a class="pt" href="javascript:void(0)" target="_blank" title="暂时不可用"><i
                                class="elegant-icon social_pinterest"></i></a></li>
                        </ul>
                      </div>
                    </div>
                    <div class="col-md-8 align-self-center">
                      <div class="post-content row">
                        <div class="col-12">
                          <div style="float:left;" class="entry-meta meta-0 font-small mb-10">
                            <div class="post-on mb-10" style="font-size:14px;">
                              <span v-for="(item,i) in toArray(data.tag)" :key="i"
                                :class="'post-cat'+' '+ isEm(item)">{{removeHtml(item)}}</span>
                            </div>
                          </div>
                        </div>

                        <div class="col-12">
                          <h5 style="float:left;" class="post-title font-weight-900 mb-20 ">
                            <a @click="$commons.toWindodBlog(data.id)" href="javascript:void(0)" style="white-space:nowrap;">
                              <div v-html="toEm(ana,data.title)"></div>
                            </a>
                            <!-- <span class="post-format-icon" v-if="data.star"><i class="elegant-icon icon_star_alt"></i></span> -->
                          </h5>
                        </div>
                        <div class="col-12">
                          <div style="float:left;" class="entry-meta meta-1 float-left font-x-small text-uppercase">
                            <div class="post-on mb-10" style="font-size:15px; line-height:20px;" v-html="data.slogan">
                            </div>
                          </div>
                        </div>
                        <div class="col-12">
                          <div style="float:left;" class="entry-meta meta-1 float-left font-x-small text-uppercase">
                            <span class="post-on">{{$commons.dateStr(data.updatetime)}} 更新</span>
                            <span class="time-reading has-dot">{{$commons.formatNumber(data.views)}} 观看</span>
                          </div>
                        </div>

                      </div>
                    </div>
                  </div>
                </article>
              </el-col>
            </el-row>

          </div>
          <el-pagination style="float:left;" layout="prev, pager, next" :total="total" :current-page="current"
            @current-change="pageChange">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  //这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  //例如：import 《组件名称》 from '《组件路径》';
  import bus from '../../utils/bus.js'
  export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {

      //这里存放数据
      return {
        currentTitle:'搜索标题',
        total: 0,
        current: 1,
        size: 10,
        hasNodata: false,
        isSearch: false,
        res: [],
        ana: [],
        searchInput: '',
        hasSearch: false,
        // 搜索 关键字
        search: "关键词搜 索🔥",
        keywords: [],
      };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
      pageChange(nc) {
        this.current = nc;
        this.searchAll();
      },
      goTop() {
        cancelAnimationFrame(this.timer)
        const self = this
        self.timer = requestAnimationFrame(function fn() {
          const oTop = document.body.scrollTop || document.documentElement.scrollTop
          if (oTop > 0) {
            document.body.scrollTop = document.documentElement.scrollTop = oTop - 50
            self.timer = requestAnimationFrame(fn)
          } else {
            cancelAnimationFrame(self.timer)
          }
        })
      },
      titleSearch() {
        // 监听事件
        bus.$on('titleSearch', res => {
          if (res.name == 'title') {
            this.currentTitle = res.data;
          }
        })
      },
      fastSearch() {
        // 监听事件
        bus.$on('fastSearch', res => {
          if (res.name == 'search') {
            this.goTop();
            this.toResult(res.data);
          }
        })
      },
      toResult(tag) {
        this.searchInput = tag;
        this.searchAll();
      },
      toEm(words, context) {
        var tmp = context;
        for (const word of words) {
          tmp = tmp.replace(new RegExp(word, "ig"), "<em style='color:red;font-style:normal;'>" + word + "</em>");
        }
        return tmp;
      },
      removeHtml(str) {
        var regex = /(<([^>]+)>)/ig
        return str.replace(regex, "");
      },
      isEm(data) {
        if (data.startsWith("<em")) {
          return 'text-danger';
        }
        return 'text-dark';
      },
      toArray(str) {
        var res = JSON.parse(str)
        return res

      },
      overflowHidForText(val, max = 42) {
        let textLength = val.length;
        let resultText = '';
        if (textLength > max) {
          resultText = val.slice(0, max) + '...'
        } else {
          resultText = val
        }
        return resultText
      },
      async searchAll() {
        if (this.$commons.isEmptyString(this.searchInput)) {
          this.searchInput = this.currentTitle == '搜索标题'?'':this.currentTitle;
          return;
        }
        this.isSearch = true;
        this.hasNodata = false;
        // 搜索
        const pram = {
          context: this.searchInput,
          current: this.current,
          size: this.size
        }
        var res = await this.$api.search.search(pram);
        const t = {
          title: this.searchInput
        }
        var tres = await this.$api.search.analyzer(t)
        if (tres.code == 20000) {
          this.ana = tres.data;
        }
        if (res.code == 20000) {
          if (res.data.length == 0) {
            this.hasNodata = true;
          }
          this.res = res.data;
          this.total = Number(res.data[0].context);
        }
        this.isSearch = false;
      },
      async getKeyWords() {
        const pram = {
          size: 10
        }
        var res = await this.$api.search.keywords(pram);
        this.keywords = res.data;
        this.$forceUpdate();
      },
      handleSelect(item) {
        this.searchAll();
      },
      async querySearchAsync(queryString, cb) {
        if (this.$commons.isEmptyString(queryString)) {
          return
        }
        // 在这里通过queryString去后端查询数据
        // cb(res)回调显示查询结果
        const pram = {
          title: queryString
        }
        var res = await this.$api.search.searchTitle(pram);
        var rs = [];
        if (res.code == 20000) {
          for (const r of res.data) {
            rs.push({
              value: r.title,
              id: r.id
            });

          }
          cb(rs)
        }

      },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {

    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
      this.titleSearch();
      this.fastSearch();
      this.getKeyWords();
    },
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  }

</script>
<style lang="scss" scoped>
 /deep/ .el-input__inner {
    border: none;
  }

 </style>
